'use client';
import './index.css';
import Image from 'next/image';
import { LoginForm, ProForm, ProFormText } from '@ant-design/pro-form';
import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import Link from 'next/link';
import { message } from 'antd';
import { useRouter } from 'next/navigation';
import { setLoginUser } from '@/store/loginUser';
import { useDispatch } from 'react-redux';
import { AppDispatch } from '@/store';
import { getLoginUserInfoUsingPost, loginUsingPost } from '@/api/UserApi';

const UserLoginPage: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const router = useRouter();
  const [form] = ProForm.useForm();
  const handleLogin = async (loginForm: API.LoginDto) => {
    try {
      const res = await loginUsingPost(loginForm);
      if (res.data) {
        message.success('登录成功');
        const res2 = await getLoginUserInfoUsingPost();
        console.log(res2);
        if (res2.data) {
          dispatch(setLoginUser(res2.data));
        } else {
        }
        router.replace('/');
        form.resetFields();
      }
    } catch (e) {
      message.error('登陆失败' + e.message);
    }
  };
  return (
    <div id="login-page">
      <LoginForm
        form={form}
        logo={<Image src="/assets/logo.png" alt="" height={44} width={44} />}
        title="NextJS - 用户登录"
        subTitle="程序员面试刷题网站"
        onFinish={handleLogin}
      >
        <ProFormText
          name="username"
          fieldProps={{
            size: 'large',
            prefix: <UserOutlined />,
          }}
          placeholder={'请输入用户名'}
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'请输入密码'}
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        />
        <div
          style={{
            marginBlockEnd: 24,
            textAlign: 'end',
          }}
        >
          还没有账号?
          <Link href={'/user/register'}>立即注册</Link>
        </div>
      </LoginForm>
    </div>
  );
};

export default UserLoginPage;
